import { Body, Get, Param, Post, Query, Req } from '@nestjs/common';
import { Controller } from '@nestjs/common';
import { ExampleUpgrade } from '../../models/example_upgrade.model';
import { Public } from '../../metadatas/public.metadata';

@Controller('/api/manage/example')
export class ExampleController {
  @Get('/')
  async gets(@Req() request: any) {
    const result = await ExampleUpgrade.findAndCountAll({
      offset: 0,
      limit: 10,
      order: [['createdAt', 'DESC']],
      attributes: { exclude: ['id', 'notice', '_version', '_version_min'] }
    });
    return Promise.resolve(result);
  }

  @Post('/')
  async add(@Req() request: any) {
    const { account_id } = request.user;
    const row: any = { account_id, example_name: '实例名', version: '1.0.1', version_min: '1.0.0' };
    await ExampleUpgrade.create(row);
    return Promise.resolve();
  }

  @Public()
  @Get('/:example_id/check')
  async check(@Param() param: Record<'example_id', string>, @Query() query: Record<'version', string>) {
    const { example_id } = param;
    if (!query.version) return Promise.reject('version 字段不能为空');
    const ins = await ExampleUpgrade.findOne({ where: { example_id }, attributes: ['id', 'download_link', 'force_updating', 'version', 'version_min', 'page_view'] });
    if (!ins) return Promise.reject('实例不存在');
    await ins.increment(['page_view']);
    const row: Record<string, any> = ins.toJSON();
    const upgradeable = this._versionDetection(query.version, row.version);
    if (upgradeable && !row.force_updating) row.force_updating = this._versionDetection(query.version, row.version_min);
    row.upgradeable = upgradeable;
    ['id', 'version_min', 'page_view'].forEach((key) => delete row[key]);
    return Promise.resolve(row);
  }

  // 版本号对比
  _versionDetection(_oldVersion: string, _newVersion: string) {
    const oldVersion = this._format_vers(_oldVersion);
    const newVersion = this._format_vers(_newVersion);
    if (!newVersion) return false;
    if (!oldVersion) return true;
    for (let index = 0; index < newVersion.length; index++) {
      const _newVer = newVersion[index];
      const _oldVer = oldVersion[index] || 0;
      if (_oldVer === _newVer) continue;
      return _oldVer < _newVer;
    }
    return false;
  }

  _format_vers(val: string): null | number[] {
    if (!val) return null;
    const str = `${val}`.trim();
    const vals = str.split('.').map((v) => ~~v.trim());
    return vals;
  }
}
